<?php
/**
 * Created by PhpStorm.
 * User: hongls
 * Date: 2016/3/24
 * Time: 9:45
 * 卡券管理
 */
namespace Admin\Controller;
use Admin\BaseController;
use Common\Model\CouponModel;
use Common\Model\BusinessModel;
use Common\Model\UtilsModel;
use Common\Model\WeixinModel;
use Common\Model\WeixinTicketModel;
use Think\Page;

class CardController extends BaseController
{
    /**
     * index 卡券列表
     */
    public function index(){
        $keyword = I('get.keyword','');
        $where = "1";
        if($keyword){
            $where .= " and title like '%$keyword%'";
        }

        $card_info = M('card_base_info',null,DB_MAIN_CFG);
        $card_code = M('card_code',null,DB_MAIN_CFG);
        
        //分页
        $count = $card_info->where($where)->count();
        $this->smarty->assign('totalDataCount',$count);

        $limit = I('get.limit',10,'int');	//每页显示条数
        $Page = new Page($count, $limit);
        fetchPage($this->smarty, $Page);
        //分页
        $list = $card_info
            ->where($where)
            ->field('id,title,stock,totalNum,consumeNum,status,authorName,type,platformSwitch,weixinDeposit')
            ->where($where)
            ->order('id desc')
            ->limit($Page->firstRow,$Page->listRows)
            ->select();

        //已领取卡券的用户
        $card_list_usesd = $card_code
                            ->field('COUNT(DISTINCT uid) AS num,cardId as id')
                            ->where('uid >0')
                            ->group('cardId')
                            ->select();

        foreach($list as $key => $value) {
            switch($value['platformSwitch']+0){
                case CouponModel::CARD_PLATFORM_BOTH:
                    $list[$key]['plat']='微信互通';
                    break;
                case CouponModel::CARD_PLATFORM_WEIXIN:
                    $list[$key]['plat']='纯微信';
                    break;
                case CouponModel::CARD_PLATFORM_STARJOY:
                    $list[$key]['plat']='自平台券';
                    break;
            }
            //合并门店数量
            foreach ($card_list_usesd as $k => $v) {
                if ($v['id'] == $value['id']) {
                    $list[$key]['num'] = $card_list_usesd[$k]['num'];
                    unset($card_list_usesd[$k]);
                } else {
                    $list[$key]['num'] = 0;
                    break;
                }
            }
        }

        //卡券平台选择
        $this->smarty->assign('CARD_PLATFORM_BOTH',CouponModel::CARD_PLATFORM_BOTH);//自平台与微信打通
        $this->smarty->assign('CARD_PLATFORM_WEIXIN',CouponModel::CARD_PLATFORM_WEIXIN);//仅微信
        $this->smarty->assign('CARD_PLATFORM_STARJOY',CouponModel::CARD_PLATFORM_STARJOY);//仅自平台,星悦

        $this->smarty->assign('cardName',$cardName);
        $this->smarty->assign('limit',$limit);
        //投放数量
        $this->smarty->assign('list',$list);
        $this->smarty->assign('keyword',$keyword);
        $this->smarty->display('Card/index.html');
    }
    /**
     * add添加卡券页面
     */
    public function add(){

        $restaurantReturn=BusinessModel::getRestaurantList();
        $restaurant_list=$restaurantReturn['data'];
        $cardType = CouponModel::getCardType();
        $plats=CouponModel::getPlatform();

        $this->smarty->assign('card_platform',$plats);

        $this->smarty->assign('restaurant_list',$restaurant_list);
        $this->smarty->assign('card_type',$cardType);
        $this->smarty->assign('card_width',C('CARD_WIDTH'));
        $this->smarty->assign('card_height',C('CARD_HEIGHT'));
        $this->smarty->display('Card/add.html');
    }


    /**
     * edit 编辑卡券
     */
    public function edit(){
        $id = I('get.id',null);
        $card_base = M('card_base_info',null,DB_MAIN_CFG);



        $item = $card_base->find($id);
        $restaurantReturn=BusinessModel::getRestaurantList();
        $restaurant_list=$restaurantReturn['data'];
        $this->smarty->assign('restaurant_list',$restaurant_list);


        $storeReturn=BusinessModel::getStoreListByRestaurantId($item['restaurantId']);
        $storeList=$storeReturn['data'];
        $this->smarty->assign('store_list',$storeList);

        $cardType = CouponModel::getCardType();
        $this->smarty->assign('card_type',$cardType);

        $plats=CouponModel::getPlatform();
        $this->smarty->assign('card_platform',$plats);

        $this->smarty->assign('obj',$item);
        $this->smarty->assign('card_width',C('CARD_WIDTH'));
        $this->smarty->assign('card_height',C('CARD_HEIGHT'));
        $this->smarty->display('Card/edit.html');

    }



    /**
     * cardUpdate 更改卡券状态
     */
    public function cardUpdate(){
        $id = I('get.id', null, 'intval');
        $card_info = M('card_base_info',null,DB_MAIN_CFG);
        $item = $card_info->find($id);
        if(empty($item)){
            $this->error('没有存在该卡券');
        }
        if($item['status']) {
            $result = $card_info->where('id=' . $id)->setField('status', ENABLE_DISABLE);
        }else{
            $result = $card_info->where('id=' . $id)->setField('status', ENABLE_ENABLE);
        }
        if ($result) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }


    /**
     * record 根据单个卡券查看该卡券使用记录
     */
    public function record(){
        $cardId     = I('get.cardId',null);
        $code       = I('get.code',null);
        $startDate  = I('get.startDate',null);
        $endDate    = I('get.endDate',null);
        $status    = I('get.status',-1,'int');
        $export		=I('get.export',0,'int');

        $card_code = M('card_code',null,DB_MAIN_CFG);

        $where='card_code.status !='.CouponModel::CODE_STATUS_DEFAULT;
        if($cardId){
            $where .=' and card_code.cardId='.$cardId;
        }
        if($status!=-1){
            $where .=' and card_code.status='.$status;
        }
        if ($code){
            $where .=" and card_code.code like '{$code}'";
        }
        if($startDate){
            $startTime=strtotime($startDate);
            $where .=" and card_code.consumeTime > {$startTime}";
        }
        if($endDate){
            $endTime=strtotime($endDate)+UtilsModel::ONE_DAY;
            $where .=" and card_code.consumeTime < {$endTime}";
        }



        if($export){
            ini_set('memory_limit', '512M');


            $sql="SELECT `code` as '卡券号',cardTitle as '卡券名称',from_unixtime(consumeTime) as '核销时间' ,vf.`verificationName` as '核销员' ,vf.`phone` as '手机' ,st.`storeName` as '门店' ,st.address as '门店地址'
 FROM `card_code` LEFT JOIN `card_base_info` on `card_code`.`cardId` =`card_base_info` .id 
left join `s_verification` as vf  on `card_code`.verificationId=vf.id
left join `s_store` as st on `card_code` .storeId=st.`id` 
where {$where}
order by consumeTime desc;";
            $data=$card_code->query($sql);

            exportExcel($data, array('卡券号','卡券名称','核销时间','核销员','手机','门店','门店地址'),'卡券日志_'.date('Ymd',time()));
            exit;
        }
        else {
            $count = $card_code
                ->where($where)
                ->count();
            $this->smarty->assign('totalDataCount',$count);

            $limit = I('get.limit',10,'int');	//每页显示条数
            $Page = new Page($count, $limit);
            //分页
            fetchPage($this->smarty, $Page);
            $list = $card_code
                ->field('card_code.status,card_code.code,card_code.consumeTime,u_user_base.nickname,u_user_base.realName,u_user_base.bindPhone')
                ->join('u_user_base on u_user_base.uid = card_code.uid')
                ->where($where)
                ->limit($Page->firstRow, $Page->listRows)
                ->select();
            $cardStatus = CouponModel::getCardUseStatus();//C('CARD_USE_TYPE');

            $card = CouponModel::getCardKv();
            $this->smarty->assign('statusType', $cardStatus);
            $this->smarty->assign('status', $status);

            $this->smarty->assign('cardList', $card);
            $this->smarty->assign('cardId', $cardId);

            $this->smarty->assign('startDate', $startDate);
            $this->smarty->assign('endDate', $endDate);
            $this->smarty->assign('code', $code);

            $this->smarty->assign('limit',$limit);
            $this->smarty->assign('list', $list);

            $this->smarty->display('Card/log.html');
        }
    }






    /**
     * ajaxAddCard ajax创建修改卡券信息表
     */
    public function ajaxAddCard(){
        $uid        = session('auth_id');
        $username   = session('username');
        $restaurantId=I('post.restaurantId',0,'int');
        $storeId    = I('post.storeId',null);
        $cardId    = I('post.id',0,'int');
        $photo      =I('post.photo');
        $platform      =I('post.platform',0,'int');

        if(!$photo){
            $ajaxData = array(
                'status' => AJAX_FASLE,
                'msg' => '卡券图片是必须的',
            );
            $this->ajaxReturn($ajaxData);
        }

        if(is_array($storeId)){
            foreach ($storeId as $k=>$v){
                if(!$v){
                    unset($storeId[$k]);
                }
            }

            //判断是否选择门店
            if(empty($storeId)){
                $ajaxData = array(
                    'status' => AJAX_FASLE,
                    'msg' => '门店必须要选择',
                );
                $this->ajaxReturn($ajaxData);
            }
        }

        $title=I('post.title',null);
        if(!$title){
            $ajaxData = array(
                'status' => AJAX_FASLE,
                'msg' => '标题必须要填写',
            );
            $this->ajaxReturn($ajaxData);
        }

        $stock=I('post.stock',0,'int');
        if($stock<1){
            $ajaxData = array(
                'status' => AJAX_FASLE,
                'msg' => '库存必须要填写',
            );
            $this->ajaxReturn($ajaxData);
        }
        $quota=I('post.quota',1,'int');
        $color=I('post.color',null);
        if(!$color){
            $ajaxData = array(
                'status' => AJAX_FASLE,
                'msg' => '颜色必须要选择',
            );
            $this->ajaxReturn($ajaxData);
        }
        $type=I('post.type',null);
        if(!$type){
            $ajaxData = array(
                'status' => AJAX_FASLE,
                'msg' => '卡券类型必须要选择',
            );
            $this->ajaxReturn($ajaxData);
        }

        $beginDate  = I('post.beginDate','');
        $endDate    = I('post.endDate','');

        $beginTimestamp = strtotime($beginDate);
        $endTimestamp   = strtotime($endDate.' 23:59:59');
        
        if(!$beginTimestamp || $beginTimestamp>$endTimestamp){
            $ajaxData = array(
                'status' => AJAX_FASLE,
                'msg' => '有效期设置错误',
            );
            $this->ajaxReturn($ajaxData);
        }

        $updateTime =time();
        $authorId   =$uid;
        $authorName =$username;


        $saveStoreId = implode(',',(array)$storeId);

        $useCustomCode  = I('post.useCustomCode',1,'int');//是否使用自定义code，1是，2否
        $depositCode    = I('post.depositCode',0,'int');//是否预存code，默认0不预存，1预存


        switch ($platform){
            case CouponModel::CARD_PLATFORM_STARJOY://自平台
                break;
            case CouponModel::CARD_PLATFORM_BOTH://互通
                break;
            default:
                $ajaxData = array(
                    'status' => AJAX_FASLE,
                    'msg' => '卡券使用平台选择错误',
                );
                $this->ajaxReturn($ajaxData);
        }


        $availableDay = I('post.availableDay',null);
        if(is_array($availableDay)){
            foreach ($availableDay as $k=>$v){
                if(!$v && $v!=='0'){
                    unset($availableDay[$k]);
                }
            }
        }
        //判断是否选择时间段
        if(empty($availableDay)){
            $ajaxData = array(
                'status' => AJAX_FASLE,
                'msg' => '可用时间段必须要选择',
            );
            $this->ajaxReturn($ajaxData);
        }

        if(is_array($availableDay)){
            $saveAvailableDay=implode(',',$availableDay);
        }else{
            $saveAvailableDay=$availableDay;
        }

        $notice         = I('post.notice');
        $description    = I('post.desc');
        $subTitle       = I('post.subTitle');
        $servicePhone   = I('post.servicePhone');
        $deal_detail    = I('post.deal_detail');

        $dbdata=array(
            'photo'     =>$photo,
            'title'     =>$title,
            'subTitle'  =>$subTitle,
            'desc'      =>$description,
            'servicePhone'=>$servicePhone,
            'deal_detail'=>$deal_detail,
            'notice'    =>$notice,
            'stock'     =>$stock,
            'totalNum'  =>$stock,
            'consumeNum'=>0,
            'quota'     =>$quota,
            'color'     =>$color,
            'type'      =>$type,
            'updateTime'=>$updateTime,
            'availableDay'=>$saveAvailableDay,
            'usefulBeginTime'=>$beginTimestamp,
            'usefulEndTime'=>$endTimestamp,
            'authorId'  =>$authorId,
            'authorName'=>$authorName,
            'storeId'   =>$saveStoreId,
            'restaurantId'=>$restaurantId
        );
        $cardBaseM   = M('card_base_info',null,DB_MAIN_CFG);
        if(!$cardId){
            if($playform=CouponModel::CARD_PLATFORM_BOTH) {//微信与平台互通
                $weixinDeposit = $depositCode == 0 ? CouponModel::WEIXIN_DEPOSIT_NONEED : CouponModel::WEIXIN_DEPOSIT_NONE;
                $dbdata['platformSwitch'] = $platform;
                $dbdata['weixinId'] = '';
                $dbdata['weixinUseCustomCode'] = $useCustomCode;
                $dbdata['weixinDeposit'] = $weixinDeposit;
                $dbdata['weixinStockRemind'] = 0;
                $dbdata['weixinCheck'] = WeixinTicketModel::WEIXIN_CHECK_DEFAULT;
            }
            $cardId=$cardBaseM->add($dbdata);
            if($cardId===false){
                $ajaxData = array(
                    'status' => AJAX_FASLE,
                    'msg' => $cardBaseM->getError(),
                );
                $this->ajaxReturn($ajaxData);
            }else{

            }
        }
        else{//修改
            if($cardBaseM->where('id='.$cardId)->save($dbdata)===false){
                $ajaxData =array(
                    'status' => AJAX_FASLE,
                    'msg' => '修改失败',
                );
            }else{
                $cardlist_data = array(
                    'cardTitle' => $title,
                    'cardId'   => $cardId,
                    'createTimestamp' => time(),
                );
                $ajaxData =array(
                    'status'    => AJAX_SUCCESS,
                    'data'      => $cardlist_data,
                    'msg'       => '修改成功',
                );
            }

            $this->ajaxReturn($ajaxData);
        }


        if($platform == CouponModel::CARD_PLATFORM_BOTH) {
            $brandName = C('SITE_NAME');
            $colorArray = array("#63b359", "#2c9f67", "#509fc9", "#5885cf", "#9062c0", "#d09a45", "#e4b138", "#ee903c", "#dd6549", "#cc463d");
            $pos = array_search($color, $colorArray) + 1;
            $weixinColor = 'Color' . str_pad($pos, 2, '0', STR_PAD_LEFT) . '0';


            $weixinStock = 0;
            $codeShowType = WeixinTicketModel::CODE_TYPE_QRCODE;
            $baseInfo = WeixinTicketModel::create_card_baseInfo($brandName, $codeShowType, $title, $subTitle, $weixinColor, $notice, $servicePhone, $description, $beginTimestamp, $endTimestamp, $weixinStock, $quota, $storeId, $useCustomCode, $depositCode);
            $weixinReturn = WeixinTicketModel::create_card_groupon($deal_detail, $baseInfo);

            if ($weixinReturn['status'] != 0) {
                $this->ajaxReturn($weixinReturn);
                $cardBaseM->where('id=' . $cardId)->delete();
                return;
            }

            //更新卡券绑定的微信卡券编号
            $cardBaseM->save(array(
                'id' => $cardId,
                'weixinId' => $weixinReturn['data']['card_id']
            ));
        }

         //根据库存生成相对应的卡券号
         $cardlist_data = array(
                    'cardTitle' => $title,
                    'cardId'   => $cardId,
                    'createTimestamp' => time(),
          );

         $ajaxData =array(
                    'status' => AJAX_SUCCESS,
                    'data' => $cardlist_data,
                    'msg' => '添加成功',
         );
        $this->ajaxReturn($ajaxData);

    }

    /**
     * ajaxAddCard ajax创建卡券号列表
     */
    public function ajaxAddCodeList(){
        $cardId     = I('post.cardId',null);
        $stock      = I('post.stock',null);
        $p          = I('post.p',null);
        $bindWeixin = I('post.bindWeixin',1,'int');

         //根据库生成一定数量的卡券列表
         $return =CouponModel::createRandomCodeList($cardId,$stock,$p,$bindWeixin);
         $p += 1;
         $data = array(
                'status' => $return['status'],
                'p' => $p,
                'msg'=>$return['msg']
         );
         if($return['status']==0){
                $data['finish']=$return['finish'];
         }

        $cardBase=CouponModel::getCardBaseInfo($cardId);
        $data['deposit']=0;
        if(CouponModel::WEIXIN_USE_CUSTOM_CODE == $cardBase['data']['weixinUseCustomCode']){
             if($cardBase['data']['weixinDeposit']==CouponModel::WEIXIN_DEPOSIT_NONEED || $cardBase['data']['weixinDeposit']==CouponModel::WEIXIN_DEPOSIT_ALL){
                 $data['deposit'] = 0;
             }else{
                 $data['deposit'] = 1;
             }
        }

        //同步微信上的库存
        if($return['finish']){
            if($cardBase['data']['platformSwitch']==CouponModel::CARD_PLATFORM_BOTH){
                $weixinCardID=$cardBase['data']['weixinId'];
                $weixinStock=WeixinTicketModel::get_card_stock($weixinCardID);
                if($cardBase['data']['stock']>$weixinStock){//库存一致，进行修正
                    $changeNum=$cardBase['data']['stock']-$weixinStock;
                    WeixinTicketModel::modifyStock($weixinCardID,$changeNum);
                }
            }


            //更新卡券的可用时间
            $updateData=array(
                'beginTimestamp'=>$cardBase['data']['usefulBeginTime'],
                'endTimestamp'=>$cardBase['data']['usefulEndTime'],
            );
            M('card_code',null,DB_MAIN_CFG)->where('cardId='.$cardId)->save($updateData);

        }

            $this->ajaxReturn($data);
    }


    /**
     * 上传微信卡券号
     * Author: shijy
     */
    public function ajaxDepositCode(){
        $cardId = I('post.cardId',null);
        if(!$cardId){
            $this->ajaxReturn(
                array('status'=>1,'msg'=>'请指定卡券')
            );
        }
        $return=CouponModel::depositWexinCard($cardId);
        $this->ajaxReturn($return);
    }
    
    /**
     * ajaxElectCard ajax 创建电子卡券
     */
    public function ajaxElectCard(){
        $uid = session('auth_id');
        $username = session('username');
        $cardInfo = M('card_base_info',null,DB_MAIN_CFG);
        $path = I('post.path',null);
        //验证数组
        $rules = array(
            array('title','require','标题必须要填写'),
            array('restaurantId','require','商户必须要选择'),
            array('color','require','颜色必须要选择'),
            array('type','require','卡券类型必须要选择'),
        );
        //自动完成数组
        $auto = array(
            array('updateTime', 'time', 3, 'function'),
            array('authorId',$uid),
            array('authorName',$username)
        );
        if($data = $cardInfo->validate($rules)->auto($auto)->create()){
            $storeId = I('post.storeId',null);
            $availableDay = I('post.availableDay',null);
            //判断是否选择门店
            if(empty($storeId)){
                $ajaxData = array(
                    'status' => AJAX_FASLE,
                    'msg' => '门店必须要选择',
                );
                $this->ajaxReturn($ajaxData);
            }
            //判断是否选择时间段
            if(empty($availableDay)){
                $ajaxData = array(
                    'status' => AJAX_FASLE,
                    'msg' => '可用时间段必须要选择',
                );
                $this->ajaxReturn($ajaxData);
            }
            //把门店和时间段 转成 **,**存入数据库
            $data['storeId'] = implode(',',$storeId);
            $data['availableDay'] = implode(',',$availableDay);
            //添加卡券基础信息表里面
            $result = $cardInfo->add($data);
            //根据库存生成相对应的卡券号
            if($result){
                $this->implodeExcel($result,$path);
                $ajaxData =array(
                    'status' => AJAX_SUCCESS,
                    'msg' => '添加成功',
                );
                $this->ajaxReturn($ajaxData);
            }else{
                $ajaxData = array(
                    'status' => AJAX_FASLE,
                    'msg' => '添加失败',
                );
                $this->ajaxReturn($ajaxData);
            }
        }else{
            $ajaxData = array(
                'status' => AJAX_FASLE,
                'msg' => $cardInfo->getError(),
            );
            $this->ajaxReturn($ajaxData);
        }
    }

    /**
     * 导入电子卡券的excel表
     * @param $cardId  卡券id
     * @param $path excel路径
     */
    function importExcel($cardId,$path){
        //导入excel
        vendor("PHPExcel.PHPExcel");
        $path = '.' . $path;
        //设置excel的类型
        $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        //打开excel的文件
        $objPHPExcel = $objReader->load($path,$encode='utf-8');
        //只获取第一页sheet
        $sheet = $objPHPExcel->getSheet(0);
        //计算行数
        $highestRow = $sheet->getHighestRow(); // 取得总行数
        $nowTime = time();
        for($i=2;$i<=$highestRow;$i++)
        {
            $datalist[] = array(
                //第一列只获取卡券号
                'code' => $objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue(),
                //第二列获取密码
                'password' => $objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue(),
                'creatTime' => $nowTime,
                'cardId' => $cardId,
            );
        }
        //计算个数
        $stock = count($datalist);

        //添加到电子卡卷表
        $result = M('elect_card_list',null,DB_MAIN_CFG)->addAll($datalist);

        if($result){
            //删除excel文件
            @unlink($path);
            //更新卡券表中的库存
            M('card_base_info',null,DB_MAIN_CFG)->where('id=' . $cardId)->setField('stock',$stock);
        }
    }
    //导入异页券excel文件
    public function uploadThirdCard()
    {
        $this->ajaxReturn(UtilsModel::excelUpload('excel',C('EXCEL_UPLOAD_DIR')));
    }

    //保存异业券基本信息并读取excel文件内容至异业券列表
    public function saveThirdCardInfo(){
        $title = I('get.title',null);
        $path = I('path',null);

        if(!$title || !$path){
            $return['id'] = 1;
            $return['msg'] = "请填写完整信息";
            $this->ajaxReturn($return);
        }
        $info = self::readAndUpdateExcel($path,'',$title);
        if($info['id']==0){
            $this->ajaxReturn(array('id'=>0,'msg'=>'导入成功','data'=>$info['msg']));
        } else{
            $this->ajaxReturn(array('id'=>1,'msg'=>$info['msg']));
        }

    }

    //新增导入异页券
    public function addImportCard(){
        $id = I('get.id',0,'intval');
        $excelName = "addInsert".$id;

        $return = UtilsModel::excelUpload($excelName,C('EXCEL_UPLOAD_DIR'));

        if($return['id'] != 0){
            //上传成功
            $this->ajaxReturn(self::readAndUpdateExcel($return['msg'],$id));
        } else{
            $this->ajaxReturn(array('id'=>1,'msg'=>$return['msg']));
        }
    }

    /**
     * 读取excel内容 并更新异页券表信息
     * author: wwl
     * @param $path excel上传路径，$id elect_card_base_info表id
     * Return: array{
     *  id:1表示出错；0表示正确；msg为提示信息
     * }
     */
    private function readAndUpdateExcel($path,$id=0,$title=''){
        $return = array('id'=>1,'msg'=>'');
        //读取excel内容
        vendor("PHPExcel.PHPExcel");
        $objPHPExcel = new \PHPExcel();
        //设置excel的类型
        $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        //打开excel的文件
        $objPHPExcel = $objReader->load($path,$encode='utf-8');
        //只获取第一页sheet
        $sheet = $objPHPExcel->getSheet(0);
        //计算行数
        $highestRow = $sheet->getHighestRow(); // 取得总行数
        $nowTime = time();

        $elect_baseM=M('elect_card_base_info',null,DB_MAIN_CFG);
        $elect_infoM=M('elect_card_list',null,DB_MAIN_CFG);
        if($id){
            $cardId = $id;
        } else{
            $data = array(
                'title'     => $title,
                'deliverNum'=> 0,
                'addTime'   => $nowTime,
                'stock'     => 0,
            );

            $cardId = $elect_baseM->add($data);
            if(!$cardId){
                $return['msg'] = "数据添加失败，请重试";
                return $return;
            }
        }
        $datalist = array();
        for($i=2;$i<=$highestRow;$i++)
        {
            $datalist[] = array(
                //第一列只获取卡卷号
                'code' => $objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue(),
                //第二列获取密码
                'password' => $objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue(),
                'creatTime' => $nowTime,
                'elcCardId' => $cardId,
            );
        }

        if($id){
            $oriList = $elect_infoM->where("elcCardId={$id}")->select();
            foreach($datalist as $key => $new){
                foreach($oriList as  $old){
                    if($new['code'] == $old['code']){
                        unset($datalist[$key]);
                    }
                }
            }
        }
        if($datalist){
            //计算个数
            $stock = count($datalist);
            //添加到电子卡卷表
            $addData = $elect_infoM->addAll($datalist);
            if($addData){
                //删除excel文件
                @unlink($path);
                //更新卡卷表中的库存
                $elect_baseM->where('id='.$cardId)->setInc('stock',$stock);
            }
        }
        $return['id'] = 0;
        $return['msg'] = $cardId;
        return $return;
    }

    //删除已保存的异页券
    public function del(){
        $id = I('get.id',0,'intval');
        $return = array('id'=>0,'msg'=>'');
        if($id<=0){
            $return['msg']="目标丢失，删除失败";
            $this->ajaxReturn($return);
        }

        $del=M('elect_card_base_info',null,DB_MAIN_CFG)->where("id={$id}")->delete();
        M('elect_card_list',null,DB_MAIN_CFG)->where("elcCardId = {$id}")->delete();
        if($del){
            $return['msg'] = "删除成功";
        } else{
            $return['msg'] = "删除失败";
        }
        $this->ajaxReturn($return);
    }

    //读取已有的异业券信息
    public function readElcCard(){
        $electCard = M('elect_card_base_info',null,DB_MAIN_CFG)->where("stock > 0")->order('addTime DESC')->select();
        $this->smarty->assign('data',$electCard);

        $id= I('get.id',$electCard[0]['id'],'intval');
        $this->smarty->assign('id',$id);

        $html = $this->smarty->fetch('Sign/thirdCardMore.html');
        $this->ajaxReturn(array('status'=>0, 'dataHtml'=>$html));
    }
}
